﻿///***************************************************************
/// 시  스  템 : Updms.Crd
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd1011m
/// 파  일  명 : Crd1011m.aspx.cs
/// 설      명 : 카드결제일관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-18 송시명   최초 작성
/// CH002  2008-10-09 송시명   결제일계산로직 수정
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd1011m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Crd1011m";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Com com = new CommCode.Com(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	// 카드코드

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SelectProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetCardInfoList();
			SetCardInfo();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region SetClientScript
		
		private void SetClientScript()
		{
			//달력콘트롤 설정
			ce_paymnt_dt.SelectedDate = DateTime.Now.AddDays(0);
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))
					{
						kw1 = ddl_search_card_cd.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_card_cd.SelectedValue = kw1;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_card_cd.SelectedValue;
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			lbl_search_keyword.Text = ddl_search_card_cd.SelectedItem.Text;
		}

		#endregion

		#region 마스터 Method (SetCardInfoList)

		// 카드정보에서 카드정보를 가져와서 ddl_search_card_cd에 채운다.
		private void SetCardInfoList()
		{
			DataSet lo_ds = new DataSet();
			Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT();

			lo_ds.Merge(_Crd1010m_NT.GetCardInfoList("Y"));

			ddl_search_card_cd.Items.Clear();
			ddl_search_card_cd.DataSource = lo_ds;
			ddl_search_card_cd.DataMember = "UPDMS_CRD_INFO";
			ddl_search_card_cd.DataTextField = "Card_Nm";
			ddl_search_card_cd.DataValueField = "Card_Cd";
			ddl_search_card_cd.DataBind();
		}

		#endregion

		#region 디테일 Method (SetCardInfo, SetDateAll, SetPaymentDtLotteCard, SetUseYn)

		//카드이미지
		private void SetCardInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), ddl_search_card_cd.SelectedValue);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//카드정보(이미지)
			using (Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT())
			{
				lo_ds.Merge(_Crd1010m_NT.GetCardInfo(lo_dp));
			}

			string ls_card_image = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Attach_File1");
			img_card_image.Src = FILE_PATH_UPLOAD_WEB_PATH + (string.IsNullOrEmpty(ls_card_image) ? "empty.png" : ls_card_image);
		}

		//모든 결제예정일을 입력한다.(카드코드, 2007-11)
		private void SetDateAll(string ls_card_cd, string ls_target_date)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			
			lo_dp.AddProperty("ls_card_cd", typeof(string), ls_card_cd);
			
			using (Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT())
			{
				lo_ds.Merge(_Crd1010m_NT.GetPaymntDtRegion(lo_dp));
			}

			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CRD_INFO"))
			{
				int li_mass_st_div		= DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_INFO", "Mass_St_Div");
				string ls_mass_st_dt	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Mass_St_Dt");
				int li_mass_ed_div		= DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_INFO", "Mass_Ed_Div");
				string ls_mass_ed_dt	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Mass_Ed_Dt");
				int li_cash_st_div		= DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_INFO", "Cash_St_Div");
				string ls_cash_st_dt	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Cash_St_Dt");
				int li_cash_ed_div		= DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_INFO", "Cash_Ed_Div");
				string ls_cash_ed_dt	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Cash_Ed_Dt");
				
				//말일처리
                ls_mass_st_dt = (ls_mass_st_dt == "32") ? DateUtil.GetLastDay(DateUtil.GetCalcMonth(ls_target_date, li_mass_st_div, "yyyy-MM")) : ls_mass_st_dt;
                ls_mass_ed_dt = (ls_mass_ed_dt == "32") ? DateUtil.GetLastDay(DateUtil.GetCalcMonth(ls_target_date, li_mass_ed_div, "yyyy-MM")) : ls_mass_ed_dt;
                ls_cash_st_dt = (ls_cash_st_dt == "32") ? DateUtil.GetLastDay(DateUtil.GetCalcMonth(ls_target_date, li_cash_st_div, "yyyy-MM")) : ls_cash_st_dt;
                ls_cash_ed_dt = (ls_cash_ed_dt == "32") ? DateUtil.GetLastDay(DateUtil.GetCalcMonth(ls_target_date, li_cash_ed_div, "yyyy-MM")) : ls_cash_ed_dt;

				//롯데카드 결제일 로직적용
				if (ls_card_cd == "") //"CC09X" -> "" - 롯데카드 예외처리 제거
				{
					SetPaymentDtLotteCard();

					//현금서비스
					txt_cash_st_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_cash_st_div, "yyyy-MM") + "-" + ls_cash_st_dt;
					txt_cash_ed_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_cash_ed_div, "yyyy-MM") + "-" + ls_cash_ed_dt;
				}
				else
				{
					//바인딩
					txt_mass_st_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_mass_st_div, "yyyy-MM") + "-" + ls_mass_st_dt;
					txt_mass_ed_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_mass_ed_div, "yyyy-MM") + "-" + ls_mass_ed_dt;
					txt_cash_st_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_cash_st_div, "yyyy-MM") + "-" + ls_cash_st_dt;
					txt_cash_ed_dt.Text = DateUtil.GetCalcMonth(ls_target_date, li_cash_ed_div, "yyyy-MM") + "-" + ls_cash_ed_dt;
				}
			}
		}

		//롯데카드 결제일 로직적용 - 2012년 1월부터 영향받음
		//시작일 :	이전이용기간 종료일 다음날
		//종료일 :	전월이 2월이면		전월 25일
		//			전월말일이 30일 이면	전월 26일
		//			전월말일이 31일 이면	전월 27일
		private void SetPaymentDtLotteCard()
		{
			string ls_paymnt_dt = txt_paymnt_dt.Text.Trim();	//결제일
			string ls_pre_ym = DateUtil.GetCalcMonth(ls_paymnt_dt, -1, "yyyy-MM");	//전월(년월)
			string ls_pre_pre_ym = DateUtil.GetCalcMonth(ls_paymnt_dt, -2, "yyyy-MM");	//전전월(년월)
			string ls_pre_month = ls_pre_ym.Substring(5, 2);//전월(월)
			string ls_pre_pre_month = ls_pre_pre_ym.Substring(5, 2);//전전월(월)
			string ls_pre_month_last_day = DateUtil.GetLastDay(ls_pre_ym);	//전월말일
			string ls_pre_pre_month_last_day = DateUtil.GetLastDay(ls_pre_pre_ym);	//전전월말일

			string ls_mass_st_dt = "";
			string ls_mass_ed_dt = "";

			//이용기간 종료일
			if (ls_pre_month == "02")
			{	//전월이 2월이면 전월 25일
				ls_mass_ed_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -1, "yyyy-MM") + "-" + "25";
			}
			else
			{
				switch (ls_pre_month_last_day)
				{
					case "30":	//전월의 마지막날이 30일이면 전월 26일
						ls_mass_ed_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -1, "yyyy-MM") + "-" + "26";
						break;
					case "31":	//전월의 마지막날이 31일이면 전월 27일
						ls_mass_ed_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -1, "yyyy-MM") + "-" + "27";
						break;
				}
			}

			//이용기간 시작일 - 이전이용기간 종료일 다음날 - 전전월의 이용기간 종료일 +1일
			if (ls_pre_pre_month == "02")
			{	//전전월이 2월이면 전월 26일
				ls_mass_st_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -2, "yyyy-MM") + "-" + "26";
			}
			else
			{
				switch (ls_pre_pre_month_last_day)
				{
					case "30":	//전전월의 마지막날이 30일이면 전월 27일
						ls_mass_st_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -2, "yyyy-MM") + "-" + "27";
						break;
					case "31":	//전전월의 마지막날이 31일이면 전월 28일
						ls_mass_st_dt = DateUtil.GetCalcMonth(ls_paymnt_dt, -2, "yyyy-MM") + "-" + "28";
						break;
				}
			}

			txt_mass_st_dt.Text = ls_mass_st_dt;
			txt_mass_ed_dt.Text = ls_mass_ed_dt;
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);

			using (Crd1011m_NT _Crd1011m_NT = new Crd1011m_NT())
			{
				li_row_count = _Crd1011m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Crd1011m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&page=");

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Crd1011m_RT _Crd1011m_RT = new Crd1011m_RT())
			{
				int li_return = _Crd1011m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Crd1011m_RT _Crd1011m_RT = new Crd1011m_RT())
			{
				int li_return = _Crd1011m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
				
				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Crd1011m_RT _Crd1011m_RT = new Crd1011m_RT())
			{
				int li_return = _Crd1011m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq",			typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Card_Cd",		typeof(string), ddl_search_card_cd.SelectedValue);
			lo_dp.AddProperty("Paymnt_Dt",		typeof(string), txt_paymnt_dt.Text);
			lo_dp.AddProperty("Mass_St_Dt",		typeof(string), txt_mass_st_dt.Text);
			lo_dp.AddProperty("Mass_Ed_Dt",		typeof(string), txt_mass_ed_dt.Text);
			lo_dp.AddProperty("Cash_St_Dt",		typeof(string), txt_cash_st_dt.Text);
			lo_dp.AddProperty("Cash_Ed_Dt",		typeof(string), txt_cash_ed_dt.Text);
			lo_dp.AddProperty("Create_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt",		typeof(string), "");
			lo_dp.AddProperty("Update_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt",		typeof(string), "");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			txt_mass_st_dt.Text = "";
			txt_mass_ed_dt.Text = "";
			txt_cash_st_dt.Text = "";
			txt_cash_ed_dt.Text = "";
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();//0.체크박스
			h_no.Value							= row.Cells[1].Text.ToString();							//1.번호
			lbl_pk.Text							= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();	//2.Seq
			ddl_search_card_cd.SelectedValue	= row.Cells[3].Text.Trim();								//3.Card_Cd
																										//4.Card_Nm
			txt_paymnt_dt.Text					= lbtn_rc.Text;											//5.Paymnt_Dt (template)
																										//6.Week_Of_Day
			txt_mass_st_dt.Text					= row.Cells[7].Text.Trim();								//7.Mass_St_Dt
			txt_mass_ed_dt.Text					= row.Cells[8].Text.Trim();								//8.Mass_Ed_Dt
			txt_cash_st_dt.Text					= row.Cells[9].Text.Trim();								//9.Cash_St_Dt
			txt_cash_ed_dt.Text					= row.Cells[10].Text.Trim();							//10.Cash_Ed_Dt
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
			SetCardInfo();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			//CheckPK(테이블명, PK컬럼, 비교할 값)
			if (global.CheckSaveMode("UPDMS_CRD_PAYMNT_DT", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_CRD_PAYMNT_DT>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_CRD_PAYMNT_DT>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);

			using (Crd1011m_NT _Crd1011m_NT = new Crd1011m_NT())
			{
				li_row_count = _Crd1011m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Crd1011m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//결제일계산
		protected void lbtn_paymnt_dt_Click(object sender, EventArgs e)
		{
			SetDateAll(ddl_search_card_cd.SelectedValue, txt_paymnt_dt.Text.Substring(0, 7)); // 2008-02
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		#endregion
	}
}
